import request from '@/utils/request'

// 查询生成表数据
export function listTable(query) {
  return request({
    url: '/code/gen/list',
    method: 'get',
    params: query
  })
}

// 查询表结构SQL
export function getTableSql(tableName) {
  console.log(`调用getTableSql API，表名: ${tableName}`)
  return request({
    url: '/code/gen/sql/' + tableName,
    method: 'get',
    timeout: 30000 // 增加超时时间到30秒
  }).then(response => {
    console.log(`getTableSql API响应:`, response)
    return response
  }).catch(error => {
    console.error(`getTableSql API错误:`, error)
    throw error
  })
}

// 查询db数据库列表
export function listDbTable(query) {
  return request({
    url: '/code/gen/db/list',
    method: 'get',
    params: query
  })
}

// 查询表详细信息
export function getGenTable(tableId) {
  return request({
    url: '/code/gen/' + tableId,
    method: 'get'
  })
}

// 修改代码生成信息
export function updateGenTable(data) {
  return request({
    url: '/code/gen',
    method: 'put',
    data: data
  })
}

// 导入表
export function importTable(data) {
  return request({
    url: '/code/gen/importTable',
    method: 'post',
    params: data
  })
}

// 预览生成代码
export function previewTable(tableId) {
  return request({
    url: '/code/gen/preview/' + tableId,
    method: 'get'
  })
}

// 删除表数据
export function delTable(tableId) {
  return request({
    url: '/code/gen/' + tableId,
    method: 'delete'
  })
}

// 生成代码
export function genCode(tableName, params) {
  return request({
    url: '/code/gen/genCode/' + tableName,
    method: 'get',
    params: params
  })
}

// 检查文件是否存在
export function checkFileExists(tableName, params) {
  return request({
    url: '/code/gen/checkExists/' + tableName,
    method: 'get',
    params: params
  })
}

// 删除生成的代码
export function deleteCode(tableName, params) {
  return request({
    url: '/code/gen/deleteCode/' + tableName,
    method: 'delete',
    params: params
  })
}

// 只删除前端代码
export function deleteFrontendCode(tableName, params) {
  const newParams = { ...params, codeType: 'frontend' };
  return request({
    url: '/code/gen/deleteCode/' + tableName,
    method: 'delete',
    params: newParams
  })
}

// 只删除后端代码
export function deleteBackendCode(tableName, params) {
  const newParams = { ...params, codeType: 'backend' };
  return request({
    url: '/code/gen/deleteCode/' + tableName,
    method: 'delete',
    params: newParams
  })
}

// 同步数据库
export function synchDb(tableName) {
  return request({
    url: '/code/gen/synchDb/' + tableName,
    method: 'get'
  })
}

// 获取系统目录
export function getSystemDirectories(query) {
  return request({
    url: '/code/gen/system/directories',
    method: 'get',
    params: query
  })
}

// 获取项目工作空间路径
export function getWorkspace() {
  return request({
    url: '/code/gen/workspace',
    method: 'get'
  })
}

// 获取项目结构
export function getProjectStructure() {
  return request({
    url: '/code/gen/project-structure',
    method: 'get'
  })
}
